﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WeChatBotSDK.Utilities
{
    /// <summary>
    /// 
    /// </summary>
    public static class 注入工具
    {
        /// <summary>
        /// 配置并启动微信服务，包括生成配置文件、复制必要的动态链接库文件和启动微信应用程序。
        /// </summary>
        /// <param name="wxPath">微信根目录路径</param>
        /// <param name="port">HTTP监听端口</param>
        /// <param name="callBackUrl">HTTP回调地址（可选）</param>
        /// <param name="cacheData">数据缓存目录（可选）使用\\结尾</param>
        /// <param name="decryptImg">是否解密图片，0=否，1=是（可选）</param>
        /// <param name="timeOut">图片下载超时时间，单位毫秒（可选）</param>
        /// <param name="flag">自定义标识（可选）</param>
        /// <param name="ver">伪装版本号（可选）</param>
        /// <param name="noHandleMsg">登录完成后忽略消息，0=否，1=是（可选）</param>
        /// <param name="autoLogin">是否自动点击登录按钮（可选，目前无效）</param>
        /// <returns>返回微信进程</returns>
        public static Process? SetupWeChat(
            string wxPath,
            string port,
            string? callBackUrl = null,
            string? cacheData = null,
            string? decryptImg = null,
            string? timeOut = null,
            string? flag = null,
            string? ver = null,
            string? noHandleMsg = null,
            string? autoLogin = null)
        {
            try
            {
                // 检查微信目录是否存在
                if (!Directory.Exists(wxPath))
                {
                    throw new DirectoryNotFoundException($"指定的微信目录路径不存在: {wxPath}");
                }

                // 配置文件路径
                string configPath = Path.Combine(wxPath, "config.json");

                // 当前程序根目录路径
                string currentDir = AppDomain.CurrentDomain.BaseDirectory;

               
                // 创建配置参数
                var config = new
                {
                    callBackUrl = callBackUrl ?? string.Empty, // 如果未提供回调地址，则默认为空
                    port = port,                               // 必填项，HTTP监听端口
                    cacheData = cacheData ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "DaenWxHookCache\\"), // 默认缓存目录
                    decryptImg = decryptImg ?? "0",             // 默认值为 0（不解密图片）
                    timeOut = timeOut ?? "5000",                // 默认图片下载超时时间为 5000 毫秒（5 秒）
                    flag = flag ?? Guid.NewGuid().ToString(),              // 自定义标识，默认自动生成Guid
                    ver = ver ?? string.Empty,                // 默认伪装版本号为空
                    noHandleMsg = noHandleMsg ??"0",           // 默认值为 0（不忽略消息）
                    autoLogin = autoLogin ?? "0"                // 默认值为 0（不自动点击登录按钮）
                };

                // 将配置参数保存为 JSON 文件
                string configJson = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); // 格式化为可读的 JSON 字符串
                File.WriteAllText(configPath, configJson); // 将 JSON 写入到指定的配置文件中
                Console.WriteLine($"配置文件已保存至: {configPath}");

                //// 将 DaenWxHook.dll  写入到微信根目录并改名为 version.dll
                //string versionDllPath = Path.Combine(wxPath, "version.dll");
                //// 从资源中读取字节数据
                //byte[] daenWxHook = Properties.Resources.DaenWxHook;
                //// 写到目标文件
                //File.WriteAllBytes(versionDllPath, daenWxHook);
                //Console.WriteLine($"已将 DaenWxHook.dll 写入到微信目录并改名为 version.dll: {versionDllPath}");

                //// 将 HPSocket4C.dll 复制到微信根目录
                //string newHPSocketPath = Path.Combine(wxPath, "HPSocket4C.dll");
                //// 从资源中读取字节数据
                //byte[] hPSocket4C = Properties.Resources.HPSocket4C;
                //// 写到目标文件
                //File.WriteAllBytes(newHPSocketPath, hPSocket4C);
                //Console.WriteLine($"已将 HPSocket4C.dll 写入到微信目录: {newHPSocketPath}");

                // 从程序根目录复制 DaenWxHook.dll 并重命名为 version.dll
                string sourceDaenWxHookPath = Path.Combine(currentDir, @"lib\DaenWxHook.dll");
                string destVersionDllPath = Path.Combine(wxPath, "version.dll");
                if (!File.Exists(sourceDaenWxHookPath))
                {
                    throw new FileNotFoundException($"未找到源文件 DaenWxHook.dll: {sourceDaenWxHookPath}");
                }
                File.Copy(sourceDaenWxHookPath, destVersionDllPath, true);
                Console.WriteLine($"已将 DaenWxHook.dll 从程序根目录复制到微信目录并改名为 version.dll: {destVersionDllPath}");

                // 从程序根目录复制 HPSocket4C.dll
                string sourceHPSocketPath = Path.Combine(currentDir, @"lib\HPSocket4C.dll");
                string destHPSocketPath = Path.Combine(wxPath, "HPSocket4C.dll");
                if (!File.Exists(sourceHPSocketPath))
                {
                    throw new FileNotFoundException($"未找到源文件 HPSocket4C.dll: {sourceHPSocketPath}");
                }
                File.Copy(sourceHPSocketPath, destHPSocketPath, true);
                Console.WriteLine($"已将 HPSocket4C.dll 从程序根目录复制到微信目录: {destHPSocketPath}");



                // 启动微信程序
                string weChatExePath = Path.Combine(wxPath, "WeChat.exe");
                if (!File.Exists(weChatExePath))
                {
                    throw new FileNotFoundException($"未找到微信主程序 WeChat.exe 文件: {weChatExePath}");
                }

                var p= Process.Start(new ProcessStartInfo
                {
                    FileName = weChatExePath, // 微信主程序路径
                    WorkingDirectory = wxPath, // 设置工作目录为微信根目录
                    UseShellExecute = true // 使用操作系统外壳执行程序
                });
                
                Console.WriteLine("微信已成功启动。");
                return p;
            }
            catch (Exception ex)
            {
                // 捕获所有异常并打印错误信息
                Console.WriteLine($"发生错误: {ex.Message}");
            }
            return null;
        }
    }
}
